//注册登录切换
document.querySelector('.goLogin').addEventListener('click', () => {
  document.querySelector('.register').style.display = 'none'
  document.querySelector('.login').style.display = 'block'
})
document.querySelector('.goRegister').addEventListener('click', () => {
  document.querySelector('.login').style.display = 'none'
  document.querySelector('.register').style.display = 'block'
})

//注册功能
document.querySelector('.register .btn-primary').addEventListener('click', async e => {
  e.preventDefault()
  const data = {
    username: document.querySelector('.register [name=username]').value,
    password: document.querySelector('.register [name=password]').value
  }
  if (data.username.length < 2 || data.username.length > 15) {
    Toast.info('用户名，长度2~15位')
    return
  }
  if (data.password.length < 6 || data.password.length > 15) {
    Toast.info('密码，长度6~15位')
    return
  }
  try {
    const res = await axios({ url: 'api/register', method: 'post', data })
    Toast.success(res.data.message)
    setTimeout(() => {
      document.querySelector('.register').style.display = 'none'
      document.querySelector('.login').style.display = 'block'
    }, 1000)
  } catch (e) {
    Toast.fail(e.response.data.message)
  }
})

//登录功能
document.querySelector('.login .btn-primary').addEventListener('click', async e => {
  e.preventDefault()
  const data = {
    username: document.querySelector('.login [name=username]').value,
    password: document.querySelector('.login [name=password]').value
  }

  if (data.username.length < 2 || data.username.length > 15) {
    Toast.info('用户名，长度2~15位')
    return
  }
  if (data.password.length < 6 || data.password.length > 15) {
    Toast.info('密码，长度6~15位')
    return
  }
  try {
    const res = await axios({ url: 'api/login', method: 'post', data })
    localStorage.setItem('token', res.data.token)
    localStorage.setItem('username', data.username)
    Toast.success(res.data.message)
    setTimeout(() => {
      location.href = './index.html'
    }, 2000)
  } catch (e) {
    Toast.fail(e.response.data.message)
  }
})